# 测试函数
function Test-API {
    param (
        [string]$Method,
        [string]$Uri,
        [object]$Body = $null,
        [string]$Token = $null
    )

    $headers = @{
        "Content-Type" = "application/json"
    }

    if ($Token) {
        $headers["Authorization"] = "Bearer $Token"
    }

    try {
        if ($Body) {
            $bodyJson = $Body | ConvertTo-Json
            $response = Invoke-WebRequest -Uri $Uri -Method $Method -Headers $headers -Body $bodyJson
        } else {
            $response = Invoke-WebRequest -Uri $Uri -Method $Method -Headers $headers
        }

        Write-Host "请求成功！"
        Write-Host "状态码: $($response.StatusCode)"
        Write-Host "响应内容:"
        $response.Content | ConvertFrom-Json | ConvertTo-Json -Depth 10
        return $response
    } catch {
        Write-Host "请求失败！"
        Write-Host "错误信息: $($_.Exception.Message)"
        if ($_.Exception.Response) {
            $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
            $reader.BaseStream.Position = 0
            $reader.DiscardBufferedData()
            $responseBody = $reader.ReadToEnd()
            Write-Host "错误响应: $responseBody"
        }
    }
}

# 1. 测试服务器状态
Write-Host "`n测试服务器状态..."
Test-API -Method Get -Uri "http://localhost:3000/health"

# 2. 注册新用户
Write-Host "`n测试用户注册..."
$registerBody = @{
    username = "testuser"
    email = "test@example.com"
    password = "password123"
}
$registerResponse = Test-API -Method Post -Uri "http://localhost:3000/api/auth/register" -Body $registerBody

# 3. 用户登录
Write-Host "`n测试用户登录..."
$loginBody = @{
    email = "test@example.com"
    password = "password123"
}
$loginResponse = Test-API -Method Post -Uri "http://localhost:3000/api/auth/login" -Body $loginBody

# 获取token
$token = ($loginResponse.Content | ConvertFrom-Json).token

# 4. 创建文章
Write-Host "`n测试创建文章..."
$articleBody = @{
    title = "测试文章"
    content = "这是一篇测试文章的内容"
}
Test-API -Method Post -Uri "http://localhost:3000/api/articles" -Body $articleBody -Token $token

# 5. 获取文章列表
Write-Host "`n测试获取文章列表..."
Test-API -Method Get -Uri "http://localhost:3000/api/articles"

# 6. 创建问题
Write-Host "`n测试创建问题..."
$qaBody = @{
    question = "这是一个测试问题？"
    content = "这是问题的详细描述"
}
Test-API -Method Post -Uri "http://localhost:3000/api/qa" -Body $qaBody -Token $token 